package com.njzxw.fs.serversys.server;

import com.njzxw.fs.commonutil.util.StringHelper;
import com.njzxw.fs.commonutil.web.BaseServer;
import com.njzxw.fs.commonutil.web.ReturnMap;
import com.njzxw.fs.serversys.bean.CfgBean;
import com.njzxw.fs.serversys.repository.CfgReq;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

@Service
public class CfgServer extends BaseServer {

    @Autowired
    private CfgReq cfgReq;

    /**
     * 获取所有的大类信息
     *
     * @param request
     * @param response
     * @return
     */
    public ReturnMap getGroup(HttpServletRequest request, HttpServletResponse response) {
        // TODO Auto-generated method stub
        returnMap.setDataMaps(cfgReq.getGroup());
        return returnMap.getSucceeReturnMap();
    }

    @Transactional
    public ReturnMap delItem(HttpServletRequest request, CfgBean cfgBean) {
        if (cfgReq.deleteBigItem(cfgBean) != 1) {
            return returnMap.getErrorReturnMap("删除失败");
        }
        if (cfgReq.deleteItem(cfgBean) < 0) {
            return returnMap.getErrorReturnMap("删除失败");
        }
        return returnMap.getSucceeReturnMap();
    }

    @Transactional
    public ReturnMap saveItem(HttpServletRequest request,CfgBean cfgBean) {

        Map<String, Object> groupMap = cfgReq.getGroupMap(cfgBean);

        if (groupMap == null || groupMap.isEmpty()) {//未查询到大类信息
            return returnMap.getErrorReturnMap("保存失败");
        }

        String is_add_item = stringHelper.get(groupMap, "is_add_item");//是否能添加
        String siglesubitem = stringHelper.get(groupMap, "siglesubitem");//是否是多项

        if (!"1".equals(siglesubitem) || ("1".equals(siglesubitem) && !"1".equals(is_add_item))) {//单项
            String[] itemids = cfgBean.getItemid();
            CfgBean cfgBeanItem = new CfgBean();
            if(itemids == null){
                if(StringUtils.isBlank(cfgBean.getItem_id())){
                    cfgBeanItem.setValues(cfgBean.getValues());
                    cfgBeanItem.setGroup_id(cfgBean.getGroup_id());
                    cfgBeanItem.setOrderby("1");
                    cfgBeanItem.setRemark("");
                    cfgBeanItem.setName("");
                    if (cfgReq.insert(cfgBeanItem) != 1) {
                        return returnMap.getErrorReturnMap("操作失败，请稍后再试");
                    }
                }else{
                    cfgBeanItem.setValues(cfgBean.getValues());
                    cfgBeanItem.setGroup_id(cfgBean.getGroup_id());
                    cfgBeanItem.setOrderby("1");
                    cfgBeanItem.setRemark("");
                    cfgBeanItem.setName("");
                    cfgBeanItem.setId(cfgBean.getItem_id());
                    if (cfgReq.updateItem(cfgBeanItem) != 1) {
                        return returnMap.getErrorReturnMap("操作失败，请稍后再试");
                    }
                }
            }else {
                for (int i = 0; i < itemids.length; i++) {
                    cfgBeanItem.setId(itemids[i]);
                    cfgBeanItem.setValues(cfgBean.getValues());
                    if (cfgReq.updateItem(cfgBeanItem) <= 0) {
                        return returnMap.getErrorReturnMap("操作失败，请稍后再试");
                    }
                }
            }
        } else {//多项
            //先进行删除操作
            if (cfgReq.deleteItem(cfgBean) < 0) {
                return returnMap.getErrorReturnMap("操作失败，请稍后再试");
            }

            if(cfgBean.getItemName() != null){
                CfgBean cfgBeanItem = new CfgBean();
                for (int i = 0; i < cfgBean.getItemName().length; i++) {
                    logger.debug(cfgBean.getItemRemark().length+""+i);
                    cfgBeanItem.setGroup_id(cfgBean.getGroup_id());
                    cfgBeanItem.setValues(cfgBean.getItemValue()[i]);
                    cfgBeanItem.setOrderby(cfgBean.getItemOrder()[i]);
                    cfgBeanItem.setRemark(cfgBean.getItemRemark()[i]);
                    cfgBeanItem.setName(cfgBean.getItemName()[i]);
                    if (cfgReq.insert(cfgBeanItem) != 1) {
                        return returnMap.getErrorReturnMap("操作失败，请稍后再试");
                    }
                }
            }
        }
        returnMap.setReturnMap("groupid", cfgBean.getGroup_id());
        return returnMap.getSucceeReturnMap();
    }

    /**
     * 获取小类信息
     *
     * @param request
     * @return
     */
    public ReturnMap getItemList(HttpServletRequest request, CfgBean cfgBean) {
        Map<String, Object> groupMap = cfgReq.getGroupMap(cfgBean);

        if (!groupMap.isEmpty()) {
            returnMap.setReturnMap("siglesubitem", StringHelper.get(groupMap, "siglesubitem"));
            returnMap.setReturnMap("is_add_item", StringHelper.get(groupMap, "is_add_item"));
            //查询出小类信息
            List<Map<String, Object>> itemList = cfgReq.getGroupItemList(cfgBean);
//            returnMap.setDataMaps( itemList);
            returnMap.setReturnMap("itemList", itemList);
            return returnMap.getSucceeReturnMaps();
        } else {
            returnMap.setReturnMaps(ReturnMap.States.ERROR1);
            return returnMap;
        }
    }

    public ReturnMap getConfig(CfgBean cfgBean) {
        Map<String,Object> map = new HashMap<>();
        List<Map<String,Object>> list = cfgReq.getConfig(cfgBean);

        for(int i=0;i<list.size();i++){
            String siglesubitem = StringHelper.get(list.get(i),"siglesubitem");//是否是多项值
            if(!map.containsKey(StringHelper.get(list.get(i),"groupcode"))){
                if("0".equals(siglesubitem)){//不是多项值
                    map.put(StringHelper.get(list.get(i),"groupcode"),StringHelper.get(list.get(i),"values"));
                }else{
                    List<Map<String,Object>> list_ = new ArrayList<>();
                    Map<String,Object> map_ = new HashMap<>();
                    map_.put("name",StringHelper.get(list.get(i),"name"));
                    map_.put("values",StringHelper.get(list.get(i),"values"));
                    map_.put("remark",StringHelper.get(list.get(i),"remark"));
                    list_.add(map_);
                    map.put(StringHelper.get(list.get(i),"groupcode"),list_);
                }
            }else{
                List<Map<String,Object>> list_ = (List<Map<String,Object>>)map.get(StringHelper.get(list.get(i),"groupcode"));
                Map<String,Object> map_ = new HashMap<>();
                map_.put("name",StringHelper.get(list.get(i),"name"));
                map_.put("values",StringHelper.get(list.get(i),"values"));
                map_.put("remark",StringHelper.get(list.get(i),"remark"));
                list_.add(map_);
            }
        }

        returnMap.setDataMaps(list);
        return returnMap.getSucceeReturnMap();
    }

    public ReturnMap getInitCfg(HttpServletRequest request, HttpServletResponse response,CfgBean cfgBean) {

        Map<String,Object> map = new HashMap<>();
        List<Map<String,Object>> groupList = cfgReq.getGroupList(cfgBean);

        for(int i=0;i<groupList.size();i++){
            String groupcode = StringHelper.get(groupList.get(i),"groupcode");
            cfgBean.setGroup_id(groupcode);
            map.put(groupcode,cfgReq.getGroupItemList(cfgBean));
        }

        returnMap.setDataMaps(map);
        return returnMap.getSucceeReturnMap();

    }

    public ReturnMap getItem(CfgBean cfgBean) {
        List<Map<String, Object>> itemList = cfgReq.getGroupItemList(cfgBean);
        returnMap.setDataMaps(itemList);
        return returnMap.getSucceeReturnMap();
    }

    public ReturnMap getCfgNew(HttpServletRequest request, HttpServletResponse response, CfgBean cfgBean) {

        List itemList = null;

        if(StringUtils.isNotBlank(cfgBean.getBack_id())){//获取备份数据
            String data = cfgReq.getBackUps(cfgBean.getBack_id());

            if("0".equals(cfgBean.getType())){//单项
                itemList = Arrays.asList( JSONObject.fromObject(data.replaceAll(":null",":\"\"")).getJSONArray("signitemList").toArray());
            }else{
                itemList = Arrays.asList( JSONObject.fromObject(data.replaceAll(":null",":\"\"")).getJSONArray("listitemList").toArray());
            }
        }else{//获取单项数据
            if("0".equals(cfgBean.getType())){//单项
                itemList = cfgReq.getGroupSignList(cfgBean);
            }else{
                itemList = cfgReq.getGroupMaxList(cfgBean);
            }
        }

        logger.debug("itemList:"+itemList);
        returnMap.setDataMaps(itemList);
        return returnMap.getSucceeReturnMap();
    }

    @Transactional
    public ReturnMap saveNew(HttpServletRequest request, HttpServletResponse response, CfgBean cfgBean) {
        //先进行备份，备份失败返回
        ReturnMap returnMap_ = back(request,response,cfgBean);

        if(returnMap_.getStates() != ReturnMap.States.SUCCEE){
            return returnMap_;
        }

        if(cfgBean.getGroup_ids() != null){
            CfgBean cfgBeanItem = new CfgBean();
            cfgBeanItem.setOper_id(cfgBean.getOper_id());
            for(int i=0;i<cfgBean.getGroup_ids().length;i++){
                if(StringUtils.isNotBlank(cfgBean.getIdss()[i])){
                    cfgBeanItem.setId(cfgBean.getIdss()[i]);
                    cfgBeanItem.setValues(cfgBean.getValuess()[i]);
                    if(cfgBean.getNames() != null){
                        cfgBeanItem.setName(cfgBean.getNames()[i]);
                    }
                    if(cfgBean.getOrderbys() != null){
                        cfgBeanItem.setOrderby(cfgBean.getOrderbys()[i]);
                    }
                    if(cfgBean.getRemarks() != null){
                        cfgBeanItem.setRemark(cfgBean.getRemarks()[i]);
                    }
                    if(cfgBean.getGroup_ids() != null){
                        cfgBeanItem.setGroup_id(cfgBean.getGroup_ids()[i]);
                    }
                    if (cfgReq.updateItem(cfgBeanItem) <= 0) {
                        return returnMap.getErrorReturnMap("操作失败，请稍后再试");
                    }
                }else{
                    cfgBeanItem.setValues(cfgBean.getValuess()[i]);
                    if(cfgBean.getNames() != null){
                        cfgBeanItem.setName(cfgBean.getNames()[i]);
                    }
                    if(cfgBean.getOrderbys() != null){
                        cfgBeanItem.setOrderby(cfgBean.getOrderbys()[i]);
                    }else{
                        cfgBeanItem.setOrderby("1");
                    }
                    cfgBeanItem.setGroup_id(cfgBean.getGroup_ids()[i]);
                    if(cfgBean.getRemarks() != null){
                        cfgBeanItem.setRemark(cfgBean.getRemarks()[i]);
                    }
                    if (cfgReq.insert(cfgBeanItem) <= 0) {
                        return returnMap.getErrorReturnMap("操作失败，请稍后再试");
                    }
                }
            }
        }

        //清除缓存信息 保存成功后重新添加
        common.clearSystem(cfgBean.getShop_id(),cfgBean.getType());
        return returnMap.getSucceeReturnMap();
    }

    @Transactional
    public ReturnMap back(HttpServletRequest request, HttpServletResponse response, CfgBean cfgBean) {

        List<Map<String, Object>> signitemList = cfgReq.getGroupSignList(cfgBean);
        List<Map<String, Object>> listitemList = cfgReq.getGroupMaxList(cfgBean);

        JSONArray jsonArraySignitemList = JSONArray.fromObject(signitemList);
        JSONArray jsonArraylistitemList = JSONArray.fromObject(listitemList);

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("signitemList",jsonArraySignitemList);
        jsonObject.put("listitemList",jsonArraylistitemList);

        Integer exc = cfgReq.insertBackUps("t_deploy_group",cfgBean.getOper_id(),jsonObject.toString());
        if(exc == null || exc <= 0){
            return returnMap.getErrorReturnMap("备份失败");
        }

        return returnMap.getSucceeReturnMap();
    }

    public ReturnMap getBackList(HttpServletRequest request, HttpServletResponse response, CfgBean cfgBean) {

        returnMap.setDataMaps(cfgReq.getBackUpsList("t_deploy_group"));

        return returnMap.getSucceeReturnMap();
    }

    public ReturnMap getBigMap(HttpServletRequest request, HttpServletResponse response, CfgBean cfgBean) {

        cfgBean = cfgReq.getBigMap(cfgBean);

        if(cfgBean != null && StringUtils.isNotBlank(cfgBean.getGroupname())){
            returnMap.setDataMaps(cfgBean);
        }else{
            return returnMap.getErrorReturnMap("获取大类数据失败");
        }

        return returnMap.getSucceeReturnMap();
    }

    public ReturnMap saveBig(HttpServletRequest request, HttpServletResponse response, CfgBean cfgBean) {

        cfgBean.setGroupcode(cfgBean.getGroupcode().toUpperCase());

        cfgBean.setItem_nums(String.valueOf(cfgBean.getItem_num()));

        //校验格式必须是  字母或者字母加小数点组成，如：AAA.AA
        if(!validator.checkValidator("^[a-zA-Z](([a-zA-Z]*)(\\.?)([a-zA-Z]+))+$",cfgBean.getGroupcode())){
            return returnMap.getErrorReturnMap("类型编码必须字母或者加.组成");
        }

        //类型编码不可重复校验
        cfgBean.setGroup_id(cfgBean.getGroupcode());
        Integer cnt = cfgReq.getGroupCodeCnt(cfgBean);
        if(cnt > 0){
            return returnMap.getErrorReturnMap("类型编码不可重复，该编码在库中已存在");
        }

        Integer exc = null;
        if(StringUtils.isNotBlank(cfgBean.getId())){
            //获取原来存在几列配置项
            cnt = cfgReq.getItemCnt(cfgBean);
            cfgBean.setItem_num(cnt-cfgBean.getItem_num());
            exc =  cfgReq.updateBig(cfgBean);
        }else{
            exc =  cfgReq.insertBig(cfgBean);
        }

        if(exc == null || exc <= 0){
            return returnMap.getErrorReturnMap("操作失败，请重新操作");
        }

        if("1".equals(cfgBean.getSiglesubitem())){//如果是多项参数，需要提前插入到item表中
            if(!"1".equals(cfgBean.getIs_add_item())){//不允许添加配置项，就需要进行手动调整
                if(cfgBean.getItem_num() > 0){//超出数量正数 需要减少
                    String items = cfgReq.getItemDelete(cfgBean);
                    if(items != null && StringUtils.isNotBlank(items)){
                        cfgBean.setIds(Arrays.asList(items.split(",")));
                        exc = cfgReq.deleteItems(cfgBean);
                        if(exc == null || exc <= 0){
                            return returnMap.getErrorReturnMap("操作失败，请重新操作");
                        }
                    }
                }else if(cfgBean.getItem_num() < 0){//负数 需要增加
                    cfgBean.setItem_num(0-cfgBean.getItem_num());
                    CfgBean cfgBean1 = new CfgBean();
                    cfgBean1.setGroup_id(cfgBean.getGroupcode());
                    cfgBean1.setState("1");
                    cfgBean1.setOper_id(cfgBean.getOper_id());
                    for(int i=0;i<cfgBean.getItem_num();i++){
                        exc = cfgReq.insert(cfgBean1);
                        if(exc == null || exc <= 0){
                            return returnMap.getErrorReturnMap("操作失败，请重新操作");
                        }
                    }
                }
            }
        }

        return returnMap.getSucceeReturnMap();
    }
}
